<?php
namespace Apps\AppApi\Method\User;

use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Models\UserAttribute;
use Apps\Common\Models\UserBase;
use PhalconPlus\Api\Common\ResultStatus;
use AliYun;
use AliYun\OSS;
use Apps\Common\Libs\PicUrl;
use Apps\Common\Models\SysAreaZipDistrictPhonecode;
use Apps\Common\Models\UserFollow;

class LoginThird extends BaseMethod
{
    /**
     * @var string
     */
    private $message = '';
    /**
     * @var int
     */
    private $success = 0;
    /**
     * @var string
     */
    private $userToken = '';
	
    private $userid='';

    public function run()
    {
        $type = $this->getDataItem('type');
        $openId = $this->getDataItem('openid');
        $nickname = $this->getDataItem('nickname');
        $cover = $this->getDataItem('cover');
        $otherData = $this->getDataItem('other_data');
        $pushId = $this->getDataItem('push_id');// push id
        $osType = $this->getDataItem('os_type');
        // 验证数据完整性
        if(empty($type) || empty($openId) || empty($nickname)) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, "业务参数不全.");
        }
        if(!in_array($type, ['weixin', 'weibo'])) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, "类型不支持.");
        }
        $attrType = 101;
        if($type == 'weibo') {
            $attrType = 102;
        }
        // 判断用户是否已经注册了
        $userId = $this->isRegister($attrType, $openId);
        if($userId === false) {
            // 注册新账号
            $userId = $this->register($type, $attrType, $openId, $nickname, $cover, $otherData);
            if($userId === false) {
                return;
            }
        }
        $info = [];
        // 获取 user token
        if ($this->saveUserAuth($this->apiAccessToken->id, $userId)) {
            $this->success = 1;
            $this->userid=$userId;
            $this->message = '登录成功!';
            $this->userToken = $this->getUserAuth()->userToken;
            $this->saveUserPushId($userId, $pushId, $osType);

            if ($model = UserBase::query()->where("user_id = {$userId}")->execute()->getFirst()) {
                $info = $model->toArray();
                $info['user_mobile'] = $info['bind_phone'] ?: $info['user_account'];

                if ($info['user_cover'] == 'default.png' && $attrType == 101) {
                    $info['user_cover'] = json_decode($otherData)->headimgurl;
                } else {
                    $info['user_cover'] = $info['user_cover'] ? PicUrl::UserCover($info['user_cover'], $this->getDi()) : '';
                }
                $info['persional_sign'] = $info['persional_sign'] ? unserialize(base64_decode($info['persional_sign'])) : '';

                // 获取城市信息
                $SysAreaZipDistrictPhonecode = new SysAreaZipDistrictPhonecode();
                $city = $SysAreaZipDistrictPhonecode->getOne($info['user_district']);
                $info['user_district'] = $city['FULL_NAME'] ?: '';

                // 加入关注数和粉丝数
                $UserFollow = new UserFollow();
                $info['follow_count'] = $UserFollow->getFollowCount($info['user_id'], 1);
                $info['fans_count'] = $UserFollow->getToFollowCount($info['user_id'], 1);

                // 删除不要的字段
                unset($info['user_account'], $info['user_password'], $info['user_state'], $info['user_addtime'], $info['is_manage']);
            }
        } else {
            $this->message = '获取User Token异常!';
        }

        if (!$info) {
            $info = [
                "user_id" => "",
                "user_nickname" => "",
                "user_cover" => "",
                "user_gender" => "0",
                "user_birthday" => "",
                "user_realname" => "",
                "user_expert" => "",
                "user_district" => "",
                "user_money" => "",
                "user_money_virtual" => "",
                "persional_sign" => "",
                "follow_count" => 0,
                "fans_count" => 0,
            ];
        }

        $info = array_merge($info, [
            'success' => $this->success,
            'user_token' => $this->userToken,
            'message' => $this->message,
            'user_id' => $this->userid,
        ]);

        $this->setResult($info);
    }

    /**
     * 是否已经注册
     * @param $attrType
     * @param $openId
     * @return bool
     */
    private function isRegister($attrType, $openId)
    {
        $attrInfo = UserAttribute::query()
            ->columns('user_id')
            ->where('attr_type = :type: AND attr_key = :key:', ['type'=>$attrType, 'key'=>$openId])
            ->execute()
            ->getFirst();
        if($attrInfo) {
            return $attrInfo->user_id;
        }
        return false;
    }

    private function register($type, $attrType, $openId, $nickname, $cover, $otherData)
    {
        // 添加基础信息
        $base = new UserBase();
        $base->user_account = '';
        $base->user_password = '';
        $base->user_nickname = $nickname;
        /* if($cover!=''){
        	$base->user_cover = $this->getConfig()->defaultCover; //'default.png';
         } */
        //$config=$this->Config()->aliyun->oss;
        $img =file_get_contents($cover);
        file_put_contents('img/1.jpg',$img);
        $oss=new OSS('dUBfr1wNHjgMnJsd','1U6ZSbOKhGBffxsopuMIKN6xCpSzUe','oss-cn-beijing.aliyuncs.com');
        $options = array();
        $object_name=time().rand(10000,99999);
        $file_path="user-cover/".date("Y/m/d")."/".$object_name.".jpg";
        $response = $oss->upload_file_by_file('meelier',$file_path,'img/1.jpg');
        unlink('img/1.jpg');
        $url=$response->header['_info']['url'];
        $url=str_replace("http://oss-cn-beijing.aliyuncs.com/meelier/","",$url);
        if ($attrType == 101) {
            $base->user_cover = json_decode($otherData)->headimgurl ?: $url;
        } else {
            $base->user_cover = $url;
        }

       // $base->user_cover=$this->getConfig()->defaultCover;

        if(!$base->save()){
            $this->databaseErrorLog($base);
            return false;
        }
        $userId = $base->user_id;
        // 保存第三方登录信息
        $attr = new UserAttribute();
        $attr->user_id = $userId;
        $attr->attr_type = 100;
        $attr->attr_key = $type;
        $attr->attr_value_json = $openId;
        if(!$attr->save()) {
            $this->databaseErrorLog($attr);
            return false;
        }
        $attr2 = new UserAttribute();
        $attr2->user_id = $userId;
        $attr2->attr_type = $attrType;
        $attr2->attr_key = $openId;
        $attr2->attr_value_json = $otherData;
        if(!$attr2->save()) {
            $this->databaseErrorLog($attr2);
            return false;
        }

        return $userId;
    }
}